package com.yhy.common.log.aspect;

import com.yhy.common.core.exception.BizException;
import com.yhy.common.core.result.Result;
import com.yhy.common.core.utils.WebUtils;
import com.yhy.common.log.enums.RequestTypeEnum;
import com.yhy.common.log.handler.AccessLogHandler;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
@Slf4j
@RequiredArgsConstructor
public class RequestAspect {

    final AccessLogHandler accessLogHandler;

    @Around("execution(* com.yhy.*.api.*Feign.*(..))")
    public Object feignAround(ProceedingJoinPoint point) {
        return handler(point, RequestTypeEnum.FEIGN);
    }

    @Around("execution(* com.yhy.*.controller.*Controller.*(..))")
    public Object webAround(ProceedingJoinPoint point) {
        return handler(point, RequestTypeEnum.WEB);
    }

    @SneakyThrows
    private Object handler(ProceedingJoinPoint point, RequestTypeEnum typeEnum) {
        Object result = null;
        try {
            result = point.proceed();
        } catch (BizException ex) {
            result = Result.fail(ex);
            throw ex;
        } catch (Throwable throwable) {
            result = Result.fail(throwable.getMessage());
            throw throwable;
        } finally {
            accessLogHandler.process(typeEnum, WebUtils.getRequest(), point, result);
        }
        return result;
    }

}
